use std::cmp::Ordering;

use graphics::{Frame, Point, Size};

use crate::contexts::{EventCtx, LayoutCtx, LifeCycleCtx, PaintCtx};
use crate::event::{Event, LifeCycle};
use crate::widget::Pod;
use crate::widget::Widget;

pub struct VerticalLayout {
    pub els: Vec<Pod>,
}

impl VerticalLayout {
    pub fn new(els: Vec<Pod>) -> Self {
        Self { els }
    }
}

impl Widget for VerticalLayout {
    fn event(&mut self, cx: &mut EventCtx, event: &Event) {
        for el in &mut self.els {
            el.event(cx, event)
        }
    }

    // К моменду вызова этого метода мы уже расставили все origin для всех Pod в els
    fn paint(&mut self, cx: &mut PaintCtx, g: &mut Frame) {
        for el in &mut self.els {
            el.paint(cx, g);
        }
    }

    fn layout(&mut self, cx: &mut LayoutCtx) -> Size {
        let mut cur_y = 0.0;
        let mut max_x = 0.0;
        for el in &mut self.els {
            let origin = Point::new(0.0, cur_y);
            el.set_origin(cx, origin);
            let size = el.layout(cx);
            cur_y += size.height;
            max_x = match max_x.partial_cmp(&size.width) {
                None => panic!("Oooops"),
                Some(Ordering::Greater) => max_x,
                _ => size.width,
            };
        }
        Size::new(max_x, cur_y)
    }

    fn lifecycle(&mut self, cx: &mut LifeCycleCtx, event: &LifeCycle) {
        for el in &mut self.els {
            el.lifecycle(cx, event);
        }
    }
}
